﻿using Sc.Cache;
using Sc.Domain;
using Sc.Persistence;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.IO;

namespace Sc.Service
{
    public class CarInfoService
    {
        private readonly CarInfoDAO dao = new CarInfoDAO();

        /// <summary>
        /// 推送消息发送
        /// </summary>

        public int Add(CarInfo model)
        {
            var tmp = dao.Add(model);
            if (tmp > 0)
            {
                ProjectCache.ClearCardInfo();
            }
            return tmp;
        }

        /// <summary>
        /// 更新一条数据
        /// </summary>
        public bool Update(CarInfo model)
        {
            ProjectCache.ClearCardInfo();
            return dao.Update(model);
        }

        /// <summary>
        /// 删除一条数据
        /// </summary>
        public bool Delete(int Id)
        {

            return dao.Delete(Id);
        }
        /// <summary>
        /// 批量删除数据
        /// </summary>
        public bool DeleteList(string idlist)
        {
            var boo = dao.DeleteList(idlist);
            if (boo)
            {
                ProjectCache.ClearCardInfo();
            }
            return boo;
        }
        /// <summary>
        /// 根据机构获取车辆
        /// <param name="orgzNo">机构ID</param>
        /// <param name="pageIndex">当前页码</param>
        /// <param name="pageSize">每页显示条数</param>
        /// </summary>
        public IList<CarInfo> GetList(int orgzNo, int pageSize, int pageIndex)
        {
            var list = ProjectCache.CarInfo.Values.Where(it => it.OrgzNo == orgzNo).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            return list;
        }
        /// <summary>
        /// 根据机构获取车辆
        /// <param name="orgzNo">机构ID</param>
        /// <param name="pageIndex">当前页码</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <param name="carNo">车牌号</param>
        /// <param name="state">状态</param>
        /// </summary>
        public CommModel<CarInfo> GetList(int orgzNo, int pageSize, int pageIndex, int state, string carNo, int carType)
        {
            CommModel<CarInfo> ent = new CommModel<CarInfo>();
            var temp = ProjectCache.CarInfo.Values.Where(it => it.OrgzNo == orgzNo).ToList();
            temp = temp.Where(it => (state == -1 || it.CarState == state) && (carType == 0 || it.CarType == carType) && (string.IsNullOrEmpty(carNo) || it.CarNo == carNo)).ToList();
            var list = temp.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            Sys.SysWebservice service = CommService.IntanceSys();
            var pid = Convert.ToInt32(ConfigurationManager.AppSettings["pid"]);
            var per = service.LoadUserByPerAndCanteen(new Sys.Permissions() { Id = pid }, orgzNo);
            foreach (var item in list)
            {
                item.CarTypeName = ProjectCache.BaseItem[item.CarType].Name;
                var tmp = per.Users.Where(it => it.Id == item.Driver).FirstOrDefault();
                item.DriverName = tmp == null ? "未设置" : tmp.Name;
            }
            ent.Data = list; ent.RecordCount = temp.Count;
            ent.PageCount = temp.Count % pageSize == 0 ? temp.Count / pageSize : Convert.ToInt32(temp.Count / pageSize) + 1;
            return ent;
        }
        /// <summary>
        /// 获取单个模型
        /// </summary>
        /// <param name="id">业务ID</param>
        /// <returns></returns>
        public CarInfo GetCarInfoById(int id)
        {
            var ent = this.dao.GetCarInfoById(id);
            Sys.SysWebservice service = CommService.IntanceSys();
            ent.DriverName = service.GetUserById(ent.Driver).Name;
            ent.CarTypeName = ProjectCache.BaseItem[ent.CarType].Name;
            return ent;
        }
        /// <summary>
        /// 根据机构获取车辆列表
        /// </summary>
        /// <param name="orgzNo">机构ID</param>
        /// <param name="type">判断条件</param>
        /// <param name="carNo">车牌号</param>
        /// <returns></returns>
        public IList<CarInfo> GetList(int orgzNo, int type, string carNo, int cartype)
        {
            var list = ProjectCache.CarInfo.Values.Where(it => it.OrgzNo == orgzNo).ToList();
            if (type == 1)
                list = list.Where(it => it.CarState == 0).ToList();
            if (!string.IsNullOrEmpty(carNo))
                list = list.Where(it => it.CarNo.Contains(carNo)).ToList();
            if (cartype != 0)
                list = list.Where(it => it.CarType == cartype).ToList();
            Sys.SysWebservice service = CommService.IntanceSys();
            var pid = Convert.ToInt32(ConfigurationManager.AppSettings["pid"]);
            var ent = service.LoadUserByPerAndCanteen(new Sys.Permissions() { Id = pid }, orgzNo);
            foreach (var item in list)
            {
                var tmp = ent.Users.Where(it => it.Id == item.Driver).FirstOrDefault();
                item.DriverName = tmp == null ? "未设置" : tmp.Name;
            }
            return list;
        }
        /// <summary>
        /// 更新车辆状态
        /// </summary>
        /// <param name="carNo">车辆ID</param>
        /// <param name="state">状态</param>
        /// <returns></returns>
        public int UpdateCarState(int carNo, int state)
        {
            var tmp = this.dao.UpdateCarState(carNo, state);
            ProjectCache.ClearCardInfo();
            return tmp;
        }
        /// <summary>
        /// 获取当前机构驾驶员
        /// </summary>
        /// <param name="orgzNo">机构ID</param>
        /// <param name="uName">用户姓名</param>
        /// <returns></returns>
        public dynamic GetDriver(int orgzNo, string uName)
        {
            Sys.SysWebservice service = CommService.IntanceSys();
            var pid = Convert.ToInt32(ConfigurationManager.AppSettings["pid"]);
            var ent = service.LoadUserByPerAndCanteen(new Sys.Permissions() { Id = pid }, orgzNo);
            if (!string.IsNullOrEmpty(uName))
            {
                var list = ent.Users.Where(it => it.Name.Contains(uName)).ToList();
                var q = from a in list
                        select new
                        {
                            Id = a.Id,
                            Name = a.Name,
                            Phone = a.Phone
                        };
                return q;
            }
            else
            {
                var q = from a in ent.Users
                        select new
                        {
                            Id = a.Id,
                            Name = a.Name,
                            Phone = a.Phone
                        };
                return q;
            }
        }

        /// <summary>
        /// 获取当前机构用户
        /// </summary>
        /// <param name="orgzNo">机构ID</param>
        /// <param name="uName">用户姓名</param>
        /// <returns></returns>
        public dynamic GetUser(int orgzNo, string uName)
        {
            Sys.SysWebservice service = CommService.IntanceSys();
            var pid = Convert.ToInt32(ConfigurationManager.AppSettings["pid"]);
            var ent = service.LoadUserByPerAndCanteen(new Sys.Permissions() { Id = pid }, orgzNo);
            if (!string.IsNullOrEmpty(uName))
            {
                var list = ent.Users.Where(it => it.Name.Contains(uName)).ToList();
                var q = from a in list
                        select new
                        {
                            Id = a.Id,
                            Name = a.Name,
                            Phone = a.Phone
                        };
                return q;
            }
            else
            {
                var q = from a in ent.Users
                        select new
                        {
                            Id = a.Id,
                            Name = a.Name,
                            Phone = a.Phone
                        };
                return q;
            }
        }
        /// <summary>
        /// 获取所有用户
        /// </summary>
        /// <param name="orgz">机构</param>
        /// <returns></returns>
        public string GetUsers(int orgz)
        {
            Sys.SysWebservice service = CommService.IntanceSys();
            return service.LoadOrgzAllUsers(orgz);
        }

        public int SendMessages(IList<TempUserModel> list, string remark)
        {
            int sucount = 0;
            for (int i = 0; i < list.Count; i++)
            {
                if (ProjectCache.UserToken.ContainsKey(list[i].UserId))
                {
                    try
                    {
                        MessageParam ent = new MessageParam();
                        ent.BusinessId = list[i].UserId;
                        ent.Content = remark;
                        ent.Title = "派车系统通知【" + DateTime.Now + "】";
                        ent.Perfix = "DRVE";
                        var mp = ProjectCache.UserToken[ent.BusinessId];
                        CommPushMessage cpm = new CommPushMessage();
                        if (mp.OsType == 0)
                        {
                            ent.UserAndroidToken = new List<string>();
                            ent.UserAndroidToken.Add(mp.Token);
                            cpm.PushMessageForAndroid(ent);
                            sucount++;
                        }
                        else
                        {
                            ent.UserIosToken = new List<string>();
                            ent.UserIosToken.Add(mp.Token);
                            cpm.PushMessageForIOS(ent);
                            sucount++;
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }
            return sucount;
        }
        /// <summary>
        /// 得到gps位置信息
        /// </summary>
        /// <param name="CarNo"></param>
        /// <returns></returns>
        public string GetGpsSite(string CarNo)
        {
            GpsWebService.GnssService service = new GpsWebService.GnssService();
            var ent = service.GetTrack(CarNo);
            return ent.Y + "," + ent.X;
        }

        /// <summary>
        /// 得到gps位置信息
        /// </summary>
        /// <param name="CarNo"></param>
        /// <returns></returns>
        public string GetGpsSitelong(string CarNo, DateTime starttime, DateTime backtime)
        {
            GpsWebService.GnssService service = new GpsWebService.GnssService();
            var set = service.GetTracks(CarNo, starttime, backtime);
            string jsonstr = "[";
            var gpstime = starttime;
            if (set != null && set.Tables.Count > 0 && set.Tables[0].Rows.Count > 0)
            {
                var table = set.Tables[0];
                temp start = new temp() { lon = double.Parse(table.Rows[0]["Lng"].ToString()), lat = double.Parse(table.Rows[0]["Lat"].ToString()) };
                temp end = new temp() { lon = double.Parse(table.Rows[table.Rows.Count - 1]["Lng"].ToString()), lat = double.Parse(table.Rows[table.Rows.Count - 1]["Lat"].ToString()) };
                List<temp> items = new List<temp>();
                jsonstr += "{\"lng\":" + start.lon + ",\"lat\":" + start.lat + "},";
                for (int i = 1; i < table.Rows.Count - 1; i++)
                {
                    temp item = new temp() { lon = double.Parse(table.Rows[i]["Lng"].ToString()), lat = double.Parse(table.Rows[i]["Lat"].ToString()) };
                    if (getDistance(start, item) && getDistance(end, item))
                    {
                        //items.Add(item);
                        jsonstr += "{\"lng\":" + item.lon + ",\"lat\":" + item.lat + "},";
                    }
                    start = item;
                }
                //int gl = 20;
                //double linecount = items.Count / gl;
                //for (int i = 1; i <= gl; i++)
                //{
                //    if (items.Count > i * linecount)
                //jsonstr += "{\"lng\":" + items[(int)(i * linecount)].lon + ",\"lat\":" + items[(int)(i * linecount)].lat + "},";
                //}
                jsonstr += "{\"lng\":" + end.lon + ",\"lat\":" + end.lat + "}";
                jsonstr += "]";
            }
            else
            {
                jsonstr = "{\"message\":\"该车行驶数据不存在！\"}";
            }

            return jsonstr;
        }

        /// <summary>
        /// 得到两点之间的距离是否大于500米
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public bool getDistance(temp start, temp end)
        {
            double lat1 = (Math.PI / 180) * start.lat;
            double lat2 = (Math.PI / 180) * end.lat;

            double lon1 = (Math.PI / 180) * start.lon;
            double lon2 = (Math.PI / 180) * end.lon;

            //      double Lat1r = (Math.PI/180)*(gp1.getLatitudeE6()/1E6);  
            //      double Lat2r = (Math.PI/180)*(gp2.getLatitudeE6()/1E6);  
            //      double Lon1r = (Math.PI/180)*(gp1.getLongitudeE6()/1E6);  
            //      double Lon2r = (Math.PI/180)*(gp2.getLongitudeE6()/1E6);  

            //地球半径  
            double R = 6371;

            //两点间距离 km，如果想要米的话，结果*1000就可以了  
            double d = Math.Acos(Math.Sin(lat1) * Math.Sin(lat2) + Math.Cos(lat1) * Math.Cos(lat2) * Math.Cos(lon2 - lon1)) * R;

            return d * 1000 > 500;
        }
    }

    public class temp
    {
        public double lat;
        public double lon;
    }
}
